import React, { useState } from "react";
import { observer } from "mobx-react";
import { Form, Modal, Upload, Steps, Button } from "antd";
import { InboxOutlined, UploadOutlined } from "@ant-design/icons";
import { Collection } from "postman-collection";
import { messageFn } from "../../../common/messageCommon/MessageCommon";
import categoryStore from "../../../category/store/CategoryStore";
import imexportStore from "../store/ImexportStore";
import "./importStyle.scss";
import IconCommon from "../../../common/IconCommon";

const { Dragger } = Upload;

// 数据类型
const IMPORT_TYPES = {
  POSTMAN: "postman",
  SWAGGER2: "swagger2",
  OPENAPI: "openapi3"
};

// 数据类型选项
const IMPORT_ITEMS = [
  { title: "Postman", value: IMPORT_TYPES.POSTMAN, icon: "postman", desc: "支持Postman Collection V2.1格式的JSON文件" },
  { title: "Swagger", value: IMPORT_TYPES.SWAGGER2, icon: "swagger", desc: "支持Swagger 2.0格式的JSON文件" },
  { title: "OpenApi", value: IMPORT_TYPES.OPENAPI, icon: "openapi", desc: "支持OpenAPI 3.0/3.1格式的JSON文件" }
];

// 步骤条配置
const STEPS = [
  { title: "上传文件" },
  { title: "格式校验" },
  { title: "版本校验" },
  { title: "导入完成" }
];

// 校验器
const FileValidator = {
  validatePostman: (json) => {
    try {
      new Collection(json);
      return true;
    } catch (error) {
      console.error('Postman validation error:', error);
      return false;
    }
  },
  validateSwagger: async (json, type) => {
    if (!json?.info?.title || !json?.paths) return false;
    return type === IMPORT_TYPES.SWAGGER2
      ? json.swagger === "2.0"
      : json.openapi?.startsWith("3.");
  }
};

// 数据类型选择组件
const ImportItem = React.memo(({ selectedItem, setSelectedItem }) => (
  <div className="import-box">
    {IMPORT_ITEMS.map(({ value, icon, title }) => (
      <div
        key={value}
        className={`import-item ${selectedItem === value ? "import-item-selected" : ""}`}
        onClick={() => setSelectedItem(value)}
      >
        <IconCommon icon={icon} className="icon-m" />
        <span>{title}</span>
      </div>
    ))}
  </div>
));


const Import = observer(({ workspaceId }) => {
  const [form] = Form.useForm();
  const [visible, setVisible] = useState(false);
  const [selectedItem, setSelectedItem] = useState(null); // 初始未选
  const [step, setStep] = useState(0);
  const [fileList, setFileList] = useState([]);
  const [fileContent, setFileContent] = useState(null);
  const [valid, setValid] = useState(false);
  const [stepStatus, setStepStatus] = useState("process");

  const { findNodeTree } = categoryStore;
  const { importData } = imexportStore;

  const resetAll = () => {
    setVisible(false);
    setSelectedItem(null);
    setStep(0);
    setFileList([]);
    setFileContent(null);
    setValid(false);
    setStepStatus("process");
    form.resetFields();
  };

  const handleSubmit = async () => {
    setStep(3);
    form.validateFields().then(values => {
      values.workspaceId = workspaceId;
      values.type = selectedItem;
      importData(values).then(res => {
        if (res.code === 0) {
          findNodeTree({ workspaceId });
          messageFn("success", "导入成功");
          resetAll();
        } else {
          setStepStatus("error");
          setStep(2);
        }
      });
    });
  };

  const validateFileFormat = async (file) => {
    try {
      const text = await file.text();
      const json = JSON.parse(text);
      setFileContent(json);
      return json;
    } catch {
      setStepStatus("error");
      return false;
    }
  };

  const validateApiVersion = async (json) => {
    let isValid = false;
    if (selectedItem === IMPORT_TYPES.POSTMAN) {
      isValid = FileValidator.validatePostman(json);
    } else {
      isValid = await FileValidator.validateSwagger(json, selectedItem);
    }
    setStepStatus(isValid ? "finish" : "error");
    return isValid;
  };

  const handleFileValidation = async (file) => {
    const json = await validateFileFormat(file);
    if (!json) {
      setValid(false);
      setStep(0);
      return false;
    }
    setStep(1);

    if (!(await validateApiVersion(json))) {
      setValid(false);
      setStep(1);
      return false;
    }

    setValid(true);
    setStep(2);
    return false;
  };

  const handleFileChange = ({ file }) => {
    if (file.status === "removed") {
      setValid(false);
      setFileList([]);
      setFileContent(null);
      setStep(0);
      setStepStatus("process");
    } else if (valid) {
      setFileList([file]);
    }
  };

  const normFile = (e) => {
    setFileList(e.fileList);
    return e.file;
  };

  const getImportItemDesc = () => {
    const item = IMPORT_ITEMS.find(item => item.value === selectedItem);
    return item ? item.desc : "请选择导入类型";
  };

  return (
    <>
      <span onClick={() => setVisible(true)} className="display-flex-gap-5">
        <UploadOutlined /> 导入
      </span>
      <Modal
        destroyOnClose
        title="导入API"
        open={visible}
        onCancel={resetAll}
        onOk={handleSubmit}
        okText="提交"
        cancelText="取消"
        centered
        width={600}
        okButtonProps={{ disabled: !valid }}
        footer={[
          selectedItem && (
            <Button key="back" onClick={() => setSelectedItem(null)}>
              上一步
            </Button>
          ),
          <Button key="cancel" onClick={resetAll}>
            取消
          </Button>,
          <Button key="submit" type="primary" onClick={handleSubmit} disabled={!valid}>
            提交
          </Button>
        ]}
      >
        <div className="import-modal">
          {!selectedItem ? (
            // 第一步：选择数据类型
            <div className="import-section" style={{height:'200px'}}>
              <h3 className="section-title">选择数据类型</h3>
              <ImportItem
                selectedItem={selectedItem}
                setSelectedItem={(type) => {
                  setSelectedItem(type);
                  setStep(0);
                }}
              />
            </div>
          ) : (
            // 后续步骤：上传及校验
            <>
              <Steps current={step} status={stepStatus} items={STEPS} className="import-steps" size="small" />
              <div className="import-section">
                <h3 className="section-title">上传文件</h3>
                <Form form={form}>
                  <Form.Item name="file" getValueFromEvent={normFile}>
                    <Dragger
                      beforeUpload={handleFileValidation}
                      fileList={fileList}
                      onChange={handleFileChange}
                      accept=".json"
                    >
                      <p className="ant-upload-drag-icon">
                        <InboxOutlined />
                      </p>
                      <div className="upload-text">
                        <p className="upload-title">点击或拖拽文件到此区域上传</p>
                        <p className="upload-desc">{getImportItemDesc()}</p>
                      </div>
                    </Dragger>
                  </Form.Item>
                </Form>
              </div>
            </>
          )}
        </div>
      </Modal>
    </>
  );
});

export default Import;
